<template>
    <el-form-item style="width: 188px;">
      <el-select v-model="form.region" placeholder="选择才能看哦" @change="handleSelectChange">
        <el-option v-for="item in cellOptions" :key="item.cellId" :label="item.cellName" :value="item.cellName" />
      </el-select>
    </el-form-item>
    <el-row>
    <el-button type="primary" @click="add()" style="margin-left: 200px; margin-top: -50px;">添加房产</el-button>
    <el-button type="success" disabled style="margin-top: -50px;">必须选择小区才可进行操作</el-button>
  </el-row>
  <el-row>
    <!-- 表格 -->
    <el-table :data="filterTableData" style="width: 100%" v-if="showTable">
      <el-table-column label="房产编号" prop="pId" />
      <el-table-column label="房产所属小区" prop="cellName" />
      <el-table-column label="栋数" prop="pRidgepole" />
      <el-table-column label="房间数" prop="pCount" />
      <el-table-column label="房产单元楼层" prop="pUnitFloor" />
      <el-table-column label="房产所属用户" prop="pUserId" />
      <el-table-column label="入住时间" prop="pStayTime" >
        <template v-slot="{ row }">
          {{formatDate(row.pStayTime)}}
          </template>
        </el-table-column>
      <el-table-column align="right">
        <template #default="scope">
          <el-button type="success" plain @click="editData(scope.row)">更新</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="zongshu"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-row>
        <!-- 添加模态框 -->
        <el-dialog v-model="dialogFormVisible" title="添加or编辑" width="500">
      <el-form :model="form">
          <el-form-item label="栋数" :label-width="formLabelWidth">
           <el-input v-model="form.pRidgepole" autocomplete="off" />
        </el-form-item>
        <el-form-item label="房间数" :label-width="formLabelWidth">
           <el-input v-model="form.pCount" autocomplete="off" />
        </el-form-item>
        <el-form-item label="房产单元楼层" :label-width="formLabelWidth">
           <el-input v-model="form.pUnitFloor" autocomplete="off" />
        </el-form-item>
        <el-form-item label="房产所属用户" :label-width="formLabelWidth">
           <el-input v-model="form.pUserId" autocomplete="off" />
        </el-form-item>
        <el-form-item label="小区名称" :label-width="formLabelWidth">
          <el-select v-model="form.cellId" placeholder="请选择小区" @change="changename">
          <el-option v-for="item in cellOptions" :key="item.cellId" :label="item.cellName" :value="item.cellName" />
      </el-select>
        </el-form-item>
      </el-form>
       <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addData()"> 确认 </el-button>
          </div>
        </template>
        
      </el-dialog>
      <!-- 编辑模态框 -->
      <el-dialog v-model="editDialogVisible" title="添加or编辑" width="500" align-center>
          <el-form :model="editForm">
            <el-form-item label="栋数">
              <el-input v-model="editForm.pRidgepole" />
            </el-form-item>
        <el-form-item label="房产所属小区">
              <el-input v-model="editForm.pCellId" />
            </el-form-item>
        <el-form-item label="房间数">
              <el-input v-model="editForm.pCount" />
            </el-form-item>
            <el-form-item label="房产所属用户">
              <el-input v-model="editForm.pUserId" />
            </el-form-item>
            <el-form-item label="房产单元楼层">
              <el-input v-model="editForm.pUnitFloor" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="closeEditDialog">关闭</el-button>
              <el-button type="primary" @click="updateData()">保存</el-button>
            </span>
          </template>
        </el-dialog>
  </template>
  <script setup>
  import { ref, reactive, onMounted, toRaw } from "vue";
  import { ElMessage } from "element-plus";
  import axios from "axios";
  const zongshu = ref(0);
  // 当前页码
  const currentPage = ref(1);
  //当前页数量
  const pageSize = ref(5);
  //查询名称
  const search = ref("");
  const filterTableData = ref([]);
  const showTable = ref(false); //表格默认为空
  const cellOptions = ref([]); // 初始化为空数组
  const idd=ref(0)
  const dialogFormVisible = ref(false); //添加模态框默认为空
  const editDialogVisible = ref(false);//编辑模态框默认为空
  const editForm = ref({
    pId: 0,
    pCellId: 0,
    pCount: 0,
    pRidgepole: "string",
    pStayTime: "2024-03-13T02:29:06.090Z",
    pUnitFloor: "string",
    pUserId: 0
    });
  const form = ref({
    region: "",
    cellId: ""
  });
  //添加功能
  const addData = () => {
      const selectedCell = cellOptions.value.find((item) => item.cellName === form.value.cellId);
      if (selectedCell) {
          const cellId = selectedCell.cellId;
          // 在发送 POST 请求之前设置数据的 cellId 属性为选中的小区 ID
          form.value.pCellId = cellId;
          // 发起添加数据的请求
          axios
              .post("/api/api/Property_management", toRaw(form.value))
              .then((response) => {
                  console.log(response.data);
                  if (response.data === 1) {
                      ElMessage.success("添加成功");
                      dialogFormVisible.value = false; // 关闭对话框
                      cx(); // 刷新页面数据
                  } else {
                      ElMessage.error("添加失败，请重试！");
                  }
              })
              .catch((error) => {
                  console.error(error);
              });
      }
  };
  //编辑功能
  const updateData = () => {
    console.log(idd.value)
    console.log(editForm.value)
      axios.put(`/api/api/Property_management?id=${idd.value}`,editForm.value)
        .then(function (response) {
          console.log(response.data);
          if (response.data) {
            ElMessage({
              message: "更新成功",
              type: "success",
            });
            closeEditDialog();
            cx(); // 刷新页面
          } else {
            ElMessage.error("更新失败，请重试！");
          }
        })
      };
  //编辑显示功能
  const editData = (row) => {
    idd.value=row.pId
    editForm.value.pCellId=row.pCellId;
    editForm.value.pId = row.pId;
    editForm.value.pRidgepole = row.pRidgepole;
    editForm.value.pCount= row.pCount;
    editForm.value.pUnitFloor = row.pUnitFloor;
    editForm.value.pUserId = row.pUserId;
    editDialogVisible.value = true;
  };
  //点击关闭按钮
  const closeEditDialog = () => {
      editDialogVisible.value = false;
  };
  //来获取小区选项的数据
  onMounted(() => {getCelloptions();});
    // 获取小区下拉选项
    function getCelloptions() {
    axios
      .get(`/api/api/Property_management/La`)
      .then((response) => {
        console.log("小区数据：", response.data);
        cellOptions.value = response.data.map(item => ({
          cellId: item.cellId,
          cellName: item.cellName
        }));
      })
      .catch((error) => {
        console.error(error);
      });
      }
    // 分页显示数量发生改变时触发
    function handleSizeChange() {
      cx();
    }
    // 分页码发生改变时触发
    function handleCurrentChange() {
      cx();
    }
    // 查询数据和总条数
    function cx() {
    console.log("页码" + currentPage.value);
    console.log("页数" + pageSize.value);
    const selectedCell = cellOptions.value.find((item) => item.cellName === form.value.region);
    const pCellId = selectedCell ? selectedCell.cellId : -1;
    // 发起 GET 请求
    axios
      .get(
        `/api/api/Property_management?ys=${pageSize.value}&ym=${currentPage.value}&name=${search.value}&pCellId=${pCellId}`
      )
      .then((response) => {
        filterTableData.value = response.data.data;
        zongshu.value = response.data.totalCount;
        console.log(filterTableData.value);
      })
      .catch((error) => {
        console.error(error);
      });
    }
    // 下拉框选择改变时触发
    function handleSelectChange() {
    const selectedCell = cellOptions.value.find((item) => item.cellName === form.value.region);
    const pCellId = selectedCell ? selectedCell.cellId : -1;
    axios
      .get(`/api/api/Property_management/GetByCellId?pCellId=${pCellId}`)
      .then((response) => {
        filterTableData.value = response.data.data;
        zongshu.value = response.data.totalCount;
        console.log(filterTableData.value);
        showTable.value = true;
      })
      .catch((error) => {
        console.error(error);
      });
    }
    //添加按钮
    function add() {
        form.value = {        // 在确认添加后清空表单数据
          pRidgepole:"",
          pCount:"",
          pUnitFloor:"",
          pUserId:""
              };
        dialogFormVisible.value = true;
    }
    //转换时间格式
    function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
  }
    </script>
  